package com.liukaixin.product.ru.business.competition.competitiondesc;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;

import com.liukaixin.product.ru.R;
import com.liukaixin.product.ru.business.team.createteam.CreateTeamActivity;
import com.liukaixin.product.ru.business.team.jointeamlist.JoinTeamListActivity;
import com.liukaixin.product.ru.business.team.teamdesc.TeamDescFragment;
import com.liukaixin.product.ru.business.user.login.LoginActivity;
import com.liukaixin.product.ru.data.model.Competition;
import com.liukaixin.product.ru.data.model.Favorite;
import com.liukaixin.product.ru.data.model.User;
import com.liukaixin.product.ru.enumerate.FavoriteTypeEnum;
import com.liukaixin.product.ru.manager.CompetitionManager;
import com.liukaixin.product.ru.util.CheckUtil;
import com.liukaixin.product.ru.util.LVCircularSmile;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by liukaixin on 16/9/18.
 */

public class CompetitionDescFragment extends Fragment
        implements CompetitionDescContract.View, View.OnClickListener {

    @NonNull
    private static final String ARGUMENT_COMPETITION_ID = "COMPETITION_ID";
    @NonNull
    private static final String ARGUMENT_COMPETITION_NAME = "COMPETITION_NAME";

    private CompetitionDescContract.Presenter presenter;

    private NestedScrollView scrollView;

    private TextView joinWayText;
    private TextView degreeText;
    private TextView signUpEndTimeText;
    private TextView introText;
    private TextView themeText;
    private TextView hostText;
    private TextView areaText;
    private TextView requireText;
    private TextView itemText;
    private TextView scheduleText;
    private TextView awardText;
    private TextView webText;

    private FloatingActionButton plusFab;
    private FloatingActionButton createTeamFab;
    private FloatingActionButton joinTeamFab;

    private Animation rotateBackward;
    private Animation rotateForward;
    private Animation fabOpen;
    private Animation fabClose;

    private Boolean isFabOpen = false;

    private FloatingActionButton favoriteFab;
    private boolean isFavorite = false;

    private LVCircularSmile smileLoading;

    private User user = CheckUtil.isLogin();

    public CompetitionDescFragment() {
        // Required an empty constructor
    }

    public static CompetitionDescFragment newInstance(@Nullable Integer competitionId,
                                                      @Nullable String competitionName) {
        Bundle arguments = new Bundle();
        arguments.putInt(ARGUMENT_COMPETITION_ID, competitionId);
        arguments.putString(ARGUMENT_COMPETITION_NAME, competitionName);
        CompetitionDescFragment fragment = new CompetitionDescFragment();
        fragment.setArguments(arguments);
        return fragment;
    }

    @Override
    public void setPresenter(@NonNull CompetitionDescContract.Presenter presenter) {
        this.presenter = checkNotNull(presenter);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_competition_desc, container, false);
        setHasOptionsMenu(true);
        setRetainInstance(true);
        return root;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // view in activity

        CollapsingToolbarLayout collapsingToolbarLayout
                = (CollapsingToolbarLayout) getActivity().findViewById(R.id.collapsingToolbarLayout);
        collapsingToolbarLayout.setTitle(CompetitionDescFragment.this.getArguments()
                .getString(ARGUMENT_COMPETITION_NAME));
        collapsingToolbarLayout.setExpandedTitleColor(
                getResources().getColor(R.color.liukx_primary_dark));
        collapsingToolbarLayout.setCollapsedTitleTextColor(
                getResources().getColor(R.color.liukx_text_primary));

        scrollView = (NestedScrollView) view.findViewById(R.id.nested_scroll);
        smileLoading = (LVCircularSmile) view.findViewById(R.id.lv_circularSmile);

        joinWayText = (TextView) view.findViewById(R.id.join_way_text);
        degreeText = (TextView) view.findViewById(R.id.degree_text);
        signUpEndTimeText = (TextView) view.findViewById(R.id.sign_up_end_time_text);
        introText = (TextView) view.findViewById(R.id.intro_text);
        themeText = (TextView) view.findViewById(R.id.theme_text);
        hostText = (TextView) view.findViewById(R.id.host_text);
        areaText = (TextView) view.findViewById(R.id.area_text);
        hostText = (TextView) view.findViewById(R.id.host_text);
        requireText = (TextView) view.findViewById(R.id.require_text);
        itemText = (TextView) view.findViewById(R.id.item_text);
        scheduleText = (TextView) view.findViewById(R.id.schedule_text);
        awardText = (TextView) view.findViewById(R.id.award_text);
        webText = (TextView) view.findViewById(R.id.web_text);

        plusFab = (FloatingActionButton) view.findViewById(R.id.plus_fab);
        plusFab.setOnClickListener(this);
        createTeamFab = (FloatingActionButton) view.findViewById(R.id.create_team_fab);
        createTeamFab.setOnClickListener(this);
        joinTeamFab = (FloatingActionButton) view.findViewById(R.id.join_team_fab);
        joinTeamFab.setOnClickListener(this);

        favoriteFab = (FloatingActionButton) getActivity().findViewById(R.id.favorite_fab);
        favoriteFab.setClickable(false);
        favoriteFab.setOnClickListener(this);

        // Set up the animations
        rotateBackward = AnimationUtils.loadAnimation(getActivity().getApplicationContext()
                , R.anim.rotate_backward);
        rotateForward = AnimationUtils.loadAnimation(getActivity().getApplicationContext()
                , R.anim.rotate_forward);
        fabOpen = AnimationUtils.loadAnimation(getActivity().getApplicationContext()
                , R.anim.list_fab_open);
        fabClose = AnimationUtils.loadAnimation(getActivity().getApplicationContext()
                , R.anim.list_fab_close);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (CheckUtil.haveNetWork(getContext())) {
            // 获取竞赛详情.
            presenter.getCompetitionDesc();
            // 判断登录状态.
            user = CheckUtil.isLogin();
            if (user != null) {
                presenter.getFavoriteStatus(user.getId());
            }
        }
    }

    @Override
    public void showError(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showData(Competition competition) {
        joinWayText.setText(CompetitionManager.handleJoinWay(competition.getJoinWay()));
        signUpEndTimeText.setText("报名截止: " + competition.getSignUpEndTime().substring(0, 16));
        degreeText.setText(competition.getDegree());
        areaText.setText(competition.getArea());
        webText.setText(competition.getWeb());
        introText.setText(Html.fromHtml(competition.getIntro()));
        themeText.setText(Html.fromHtml(competition.getTheme()));
        hostText.setText(Html.fromHtml(competition.getHost()));
        requireText.setText(Html.fromHtml(competition.getRequire()));
        itemText.setText(Html.fromHtml(competition.getItem()));
        scheduleText.setText(Html.fromHtml(competition.getSchedule()));
        awardText.setText(Html.fromHtml(competition.getAward()));

    }


    @Override
    public void showLoading() {
        smileLoading.setVisibility(View.VISIBLE);
        smileLoading.startAnim();
    }

    @Override
    public void hideLoading() {
        smileLoading.stopAnim();
        smileLoading.setVisibility(View.GONE);
    }

    @Override
    public void makeScrollViewVisible() {
        scrollView.setVisibility(View.VISIBLE);
    }

    @Override
    public void makeFavoriteFabClickable() {
        favoriteFab.setClickable(true);
    }

    @Override
    public void makeFavorited() {
        isFavorite = true;
        favoriteFab.setImageResource(R.drawable.have_favorite);
    }

    @Override
    public void makeUnFavorited() {
        isFavorite = false;
        favoriteFab.setImageResource(R.drawable.favorite);
    }

    @Override
    public void makeFavoriteFabUnClickable() {
        favoriteFab.setClickable(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.plus_fab:
                fabClicked();
                break;
            case R.id.create_team_fab:
                fabClicked();
                toCreateTeamActivity();
                break;
            case R.id.join_team_fab:
                fabClicked();
                toJoinTeamActivity();
                break;
            case R.id.favorite_fab:
                favoriteFabClicked();
                break;
            default:
                break;
        }
    }

    private void favoriteFabClicked() {
        if (user != null) {
            if (CheckUtil.haveNetWork(getContext())) {
                if (isFavorite) {
                    presenter.cancelFavorite(user.getId());
                } else {
                    Favorite favorite = new Favorite();
                    favorite.setCategory(FavoriteTypeEnum.COMPETITION.getTypeCode());
                    favorite.setStarId(CompetitionDescFragment.this
                            .getArguments().getInt(ARGUMENT_COMPETITION_ID));
                    favorite.setUserId(user.getId());
                    favorite.setStarName(
                            CompetitionDescFragment.this.getArguments()
                                    .getString(ARGUMENT_COMPETITION_NAME));
                    presenter.doFavorite(favorite);
                }
            }
        } else {
            toLoginActivity();
        }
    }

    private void toLoginActivity() {
        Intent toLogin = new Intent(getContext(), LoginActivity.class);
        startActivity(toLogin);
    }

    private void toCreateTeamActivity() {
        if (CheckUtil.isLogin() != null) {
            Intent createTeamActivity = new Intent(getContext(), CreateTeamActivity.class);
            createTeamActivity.putExtra(CreateTeamActivity.EXTRA_COMPETITION_ID,
                    this.getArguments().getInt(CompetitionDescFragment
                            .ARGUMENT_COMPETITION_ID));
            createTeamActivity.putExtra(CreateTeamActivity.EXTRA_COMPETITION_NAME,
                    this.getArguments().getString(CompetitionDescFragment
                            .ARGUMENT_COMPETITION_NAME));
            startActivity(createTeamActivity);
        } else {
            toLoginActivity();
        }
    }

    private void toJoinTeamActivity() {
        Intent toJoinTeamActivity = new Intent(getContext(), JoinTeamListActivity.class);
        toJoinTeamActivity.putExtra(JoinTeamListActivity.EXTRA_COMPETITION_ID,
                this.getArguments().getInt(CompetitionDescFragment.ARGUMENT_COMPETITION_ID));
        startActivity(toJoinTeamActivity);
    }

    private void fabClicked() {
        if (isFabOpen) {
            plusFab.startAnimation(rotateBackward);
            createTeamFab.startAnimation(fabClose);
            createTeamFab.setClickable(false);
            joinTeamFab.startAnimation(fabClose);
            joinTeamFab.setClickable(false);
            isFabOpen = false;
        } else {
            plusFab.startAnimation(rotateForward);
            createTeamFab.startAnimation(fabOpen);
            createTeamFab.setClickable(true);
            joinTeamFab.startAnimation(fabOpen);
            joinTeamFab.setClickable(true);
            isFabOpen = true;
        }
    }
}
